package com.aya.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import java.util.ArrayList;
import java.util.List;

public class ListFactoryBean implements FactoryBean<List>, BeanFactoryAware {
    private String genericClass;
    private ConfigurableListableBeanFactory beanFactory;

    public void setGenericClass(String genericClass) {
        this.genericClass = genericClass;
    }


    @Override
    public List getObject() throws Exception {
        List list = new ArrayList();
        Class<?> beanClass = beanFactory.getBeanClassLoader().loadClass(genericClass);
        String[] beanNamesForType = beanFactory.getBeanNamesForType(beanClass, false, false);
        for (String beanName : beanNamesForType) {
            Object bean = beanFactory.getBean(beanName);
            list.add(bean);
        }
        return list;
    }

    @Override
    public Class<?> getObjectType() {
        return List.class;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {

        this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
    }
}
